package com.nbsaas.nbmall.statistics.rest.resource;

import com.haoxuer.bigworld.member.data.entity.TenantUser;
import com.haoxuer.discover.data.utils.DateUtils;
import com.nbsaas.nbmall.statistics.api.apis.VisitPageApi;
import com.nbsaas.nbmall.statistics.api.domain.list.VisitPageList;
import com.nbsaas.nbmall.statistics.api.domain.page.VisitPagePage;
import com.nbsaas.nbmall.statistics.api.domain.request.*;
import com.nbsaas.nbmall.statistics.api.domain.response.VisitPageResponse;
import com.nbsaas.nbmall.statistics.data.dao.VisitDayDao;
import com.nbsaas.nbmall.statistics.data.dao.VisitPageDao;
import com.nbsaas.nbmall.statistics.data.dao.VisitPageDayDao;
import com.nbsaas.nbmall.statistics.data.entity.VisitDay;
import com.nbsaas.nbmall.statistics.data.entity.VisitPage;
import com.nbsaas.nbmall.statistics.data.entity.VisitPageDay;
import com.nbsaas.nbmall.statistics.rest.convert.VisitPageResponseConvert;
import com.nbsaas.nbmall.statistics.rest.convert.VisitPageSimpleConvert;
import com.haoxuer.bigworld.tenant.data.entity.Tenant;
import com.haoxuer.discover.config.utils.ConverResourceUtils;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.data.page.Page;
import com.haoxuer.discover.data.page.Pageable;
import com.haoxuer.discover.data.utils.FilterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.haoxuer.bigworld.member.rest.conver.PageableConver;
import com.haoxuer.bigworld.tenant.util.TenantBeanUtils;
import com.haoxuer.bigworld.member.data.dao.TenantUserDao;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Component
public class VisitPageResource implements VisitPageApi {

    @Autowired
    private VisitPageDao dataDao;

    @Autowired
    private TenantUserDao userDao;

    @Autowired
    private VisitPageDayDao userDayDao;

    @Autowired
    private VisitDayDao visitDayDao;


    @Override
    public VisitPageResponse create(VisitPageDataRequest request) {
        VisitPageResponse result = new VisitPageResponse();

        VisitPage bean = new VisitPage();
        bean.setTenant(Tenant.fromId(request.getTenant()));
        handleData(request, bean);
        dataDao.save(bean);
        result = new VisitPageResponseConvert().conver(bean);
        return result;
    }

    @Override
    public VisitPageResponse visit(VisitPageDataRequest request) {
        VisitPageResponse result = new VisitPageResponse();
        if (StringUtils.isEmpty(request.getPath())) {
            result.setCode(501);
            result.setMsg("没有访问路径");
            return result;
        }
        String key = DateUtils.simple(new Date());
        VisitPage bean = dataDao.one(Filter.eq("tenant.id", request.getTenant()),
                Filter.eq("key", key), Filter.eq("path", request.getPath()),
                Filter.eq("user.id", request.getUser()));
        if (bean == null) {
            bean = new VisitPage();
            bean.setKey(key);
            bean.setUser(TenantUser.fromId(request.getUser()));
            bean.setPath(request.getPath());
            bean.setTenant(Tenant.fromId(request.getTenant()));
            bean.setNum(0L);
            dataDao.save(bean);
        }
        Long num = bean.getNum();
        if (num == null) {
            num = 0L;
        }
        num++;
        bean.setNum(num);


        VisitPageDay userDay = userDayDao.one(Filter.eq("tenant.id", request.getTenant()),
                Filter.eq("key", key),
                Filter.eq("user.id", request.getUser()));
        if (userDay == null) {
            userDay = new VisitPageDay();
            userDay.setKey(key);
            if (request.getUser()!=null){
                userDay.setUser(TenantUser.fromId(request.getUser()));
            }
            userDay.setTenant(Tenant.fromId(request.getTenant()));
            userDay.setPageNum(0L);
            userDayDao.save(userDay);
        }
        Long pageNum = userDay.getPageNum();
        if (pageNum == null) {
            pageNum = 0L;
        }
        pageNum++;
        userDay.setPageNum(pageNum);

        VisitDay visitDay = visitDayDao.one(Filter.eq("tenant.id", request.getTenant()),
                Filter.eq("key", key));
        if (visitDay == null) {
            visitDay = new VisitDay();
            visitDay.setKey(key);
            visitDay.setTenant(Tenant.fromId(request.getTenant()));
            visitDay.setPageNum(0L);
            visitDay.setUserNum(1L);
            visitDayDao.save(visitDay);
        }
        Long visitNum = visitDay.getPageNum();
        if (visitNum == null) {
            visitNum = 0L;
        }
        visitNum++;
        visitDay.setPageNum(visitNum);

        Long userNum = userDayDao.handle("count", "id",
                Filter.eq("tenant.id", request.getTenant()),
                Filter.eq("key", key));
        if (userNum == null) {
            userNum = 0L;
        }
        visitDay.setUserNum(userNum);
        return result;
    }

    @Override
    public VisitPageResponse update(VisitPageDataRequest request) {
        VisitPageResponse result = new VisitPageResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        VisitPage bean = dataDao.findById(request.getId());
        if (bean == null) {
            result.setCode(502);
            result.setMsg("无效id");
            return result;
        }
        handleData(request, bean);
        result = new VisitPageResponseConvert().conver(bean);
        return result;
    }

    private void handleData(VisitPageDataRequest request, VisitPage bean) {
       TenantBeanUtils.copyProperties(request,bean);
           if(request.getUser()!=null){
              bean.setUser(userDao.findById(request.getUser()));
           }

    }

    @Override
    public VisitPageResponse delete(VisitPageDataRequest request) {
        VisitPageResponse result = new VisitPageResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        dataDao.deleteById(request.getTenant(),request.getId());
        return result;
    }

    @Override
    public VisitPageResponse view(VisitPageDataRequest request) {
        VisitPageResponse result=new VisitPageResponse();
        VisitPage bean = dataDao.findById(request.getTenant(), request.getId());
        if (bean==null){
            result.setCode(1000);
            result.setMsg("无效id");
            return result;
        }
        result=new VisitPageResponseConvert().conver(bean);
        return result;
    }
    @Override
    public VisitPageList list(VisitPageSearchRequest request) {
        VisitPageList result = new VisitPageList();

        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("tenant.id", request.getTenant()));
        filters.addAll(FilterUtils.getFilters(request));
        List<Order> orders = new ArrayList<>();
        if ("asc".equals(request.getSortMethod())){
           orders.add(Order.asc(""+request.getSortField()));
        }
        else if ("desc".equals(request.getSortMethod())){
           orders.add(Order.desc(""+request.getSortField()));
        }else{
           orders.add(Order.desc("id"));
        }
        List<VisitPage> organizations = dataDao.list(0, request.getSize(), filters, orders);

        VisitPageSimpleConvert convert=new VisitPageSimpleConvert();
        ConverResourceUtils.converList(result, organizations,convert);
        return result;
    }

    @Override
    public VisitPagePage search(VisitPageSearchRequest request) {
        VisitPagePage result=new VisitPagePage();
        Pageable pageable = new PageableConver().conver(request);
        pageable.getFilters().addAll(FilterUtils.getFilters(request));
        pageable.getFilters().add(Filter.eq("tenant.id", request.getTenant()));
        if ("asc".equals(request.getSortMethod())){
            pageable.getOrders().add(Order.asc(""+request.getSortField()));
        }
        else if ("desc".equals(request.getSortMethod())){
            pageable.getOrders().add(Order.desc(""+request.getSortField()));
        }else{
            pageable.getOrders().add(Order.desc("id"));
        }
        Page<VisitPage> page=dataDao.page(pageable);

        VisitPageSimpleConvert convert=new VisitPageSimpleConvert();
        ConverResourceUtils.converPage(result,page,convert);
        return result;
    }
}
